package tr.edu.metu.is.mega.client.course.instructor.students;

import java.util.List;

import tr.edu.metu.is.mega.client.core.EditDialog;
import tr.edu.metu.is.mega.client.resource.MEGAResourceBundle;
import tr.edu.metu.is.mega.client.resource.MEGAResources;
import tr.edu.metu.is.mega.client.widgets.MegaTextField;
import tr.edu.metu.is.mega.common.dto.BaseDTO;
import tr.edu.metu.is.mega.common.dto.CourseDTO;
import tr.edu.metu.is.mega.common.dto.CourseStudentDTO;
import tr.edu.metu.is.mega.common.dto.TeamDTO;

import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.layout.FormData;

/**
 * Edit dialog for teams.
 */
public class TeamEditDialog extends EditDialog<TeamDTO> {

    private MEGAResourceBundle resourceBundle;

    private CourseDTO course;

    private MegaTextField teamNameField;

    private CourseStudentField membersField;

    private HiddenField<String> logoField;

    private Integer id;

    /**
     * Default constructor.
     */
    public TeamEditDialog(CourseDTO course) {
        super(TeamDTO.class.getName(), course);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void beforeInitForm(BaseDTO baseDTO) {
        course = (CourseDTO) baseDTO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initForm(FormPanel parent, Object... params) {
        setSize(340, 160);
        setHeading("Edit Team");

        resourceBundle = MEGAResources.RESOURCEBUNDLE;

        logoField = new HiddenField<String>();
        logoField.setName(TeamDTO.FIELD_LOGO);
        parent.add(logoField);

        teamNameField = new MegaTextField(TeamDTO.FIELD_TEAM_NAME);
        teamNameField.setFieldLabel(resourceBundle.teamManagementTeamName());
        parent.add(teamNameField, new FormData("96%"));

        membersField = new CourseStudentField(TeamDTO.FIELD_MEMBERS, course);
        membersField.setFieldLabel(resourceBundle.teamManagementTeamMembers());
        parent.add(membersField, new FormData("96%"));

    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    protected TeamDTO guiToDTO() {
        TeamDTO teamDTO = new TeamDTO();
        teamDTO.setPkid(id);
        teamDTO.setCourse(course);
        teamDTO.setMembers((List<CourseStudentDTO>) membersField.getValue());
        teamDTO.setTeamName(teamNameField.getValue());
        teamDTO.setLogo(logoField.getValue());
        return teamDTO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void dtoToGUI(TeamDTO dto) {
        id = dto.getPkid();
        membersField.setValue(dto.getMembers());
        teamNameField.setValue(dto.getTeamName());
        course = dto.getCourse();
        logoField.setValue(dto.getLogo());
    }

}
